package httphandle

import (
	"emb/emb_server/util/dbutil"
	"emb/emb_server/util/handleutil"
	"encoding/json"
	"fmt"
	"net/http"
)

// s objectID  string,nickname string,icon string,customInfo string
// r Message string,
func alterObjectData(w http.ResponseWriter, r *http.Request) {
	httpCode := http.StatusOK
	info := "success"
	var information interface{}

	fmt.Println("请求方IP地址：", r.RemoteAddr)
	defer func() {
		handleutil.SendMsg(w, httpCode, info, information)
	}()

	setHeader(w)

	err := r.ParseForm()
	if err != nil {
		httpCode = http.StatusBadRequest
		info = "参数解析失败！请使用x-www-form-urlencoded格式传输参数数据！"
		return
	}

	id := r.Form["objectID "]
	nickName := r.Form["nickname"]
	icon := r.Form["icon"]

	customJson := make(map[string]interface{})

	n := len(r.Form["customInfo"])
	result := ""
	for i := 0; i < n; i++ {
		result = result + r.Form["custom"][i]
	}

	customJson["custom"] = result

	custom, err := json.Marshal(customJson)

	fmt.Println("sendMessage:", id)
	fmt.Println("sendMessage:", nickName)
	fmt.Println("sendMessage:", icon)
	fmt.Println("sendMessage:", string(custom))

	info, ok := updateObject(id[0], nickName[0], icon[0], custom)
	if !ok {
		httpCode = http.StatusBadRequest

	}

}

func updateObject(id string, nickName string, icon string, custom []byte) (string, bool) {
	info := "success"
	sql := "update objects set nickname = $1, icon = $2,custom = $3 where id = $4"
	// sql := "update objects set nickname = $1, icon = $2 where id = $3"
	if id == "" {
		info = "objectid  is null"
		return info, false
	}

	fmt.Println(id)
	fmt.Println(nickName)
	fmt.Println(icon)
	fmt.Println(string(custom))

	dbutil.InitDb()
	db := dbutil.GetDb()
	defer dbutil.CloseDb(db)

	stmt, err := db.Prepare(sql)
	defer stmt.Close()
	if err != nil {
		fmt.Println("From:alterObjectData.Prepare")
		info = "From:alterObjectData.Prepare" + err.Error()
		return info, false
	}

	_, err = stmt.Exec(nickName, icon, custom, id)
	if err != nil {
		fmt.Println("From:alterObjectData.Exec")
		info = "From:alterObjectData.Exec" + err.Error()
		return info, false
	}
	return info, true
}
